#include <fstream>
#include <iostream>
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::string;

string file;

void test0()
{
    ifstream ifs("1_io.cc");
    if(!ifs) {
        cout << "ifstream open file error\n";
        return;
    }

    //先将文件游标偏移到文件末尾
    ifs.seekg(0, std::ios::end);//
    long length = ifs.tellg();
    cout << "length:" << length << endl;

    //读取整个文件的内容
    ifs.seekg(0);
    char * pbuff = new char[length + 1]();
    ifs.read(pbuff, length);

    file = pbuff;
    cout << "file:" << file << endl;

    ifs.close();
    delete [] pbuff;//记得回收
}

void test1()
{
    string filename("mytest.txt");
    //文件输出流没有文件时，直接创建一个新文件
    //
    //当文件存在时，会直接清空文件的内容
    ofstream ofs(filename);
    if(!ofs) {
        cout << "ofstream open file error\n";
        return;
    }

    ofs << file;

    ofs.close();
}

void test2()
{
    string filename("mytest.txt");
    ofstream ofs(filename,  std::ios::app);
    if(!ofs) {
        cout << "ofstream open file error\n";
        return;
    }

    cout << ofs.tellp() << endl;
    ofs.seekp(0);
    cout << ofs.tellp() << endl;

    string test("this is a new line\n");
    ofs << test << endl;
    //cout << ofs.tellp() << endl;
    ofs.close();
}


int main()
{
    /* test0(); */
    /* test1(); */
    test2();
    return 0;
}

